package com.eventur;



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ImageView;

public class MainActivity extends Activity 
{
	protected ImageView imageView;
	//protected Button cancelButton;
	protected InitTask initTask;

	final static String RSS_FEED_SOURCE="http://eventur.sis.pitt.edu/home.rss";
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void onResume(){
		super.onResume();
	}
	
	@Override
	public void onCreate( Bundle savedInstanceState ) 
	{
		super.onCreate(savedInstanceState);

		setContentView( R.layout.main );

		//checking if the phone is online
		try {
		    // Create a URL for the desired page
		    URL url = new URL("http://www.google.com/");

		    // Read all the text returned by the server
		    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
		    @SuppressWarnings("unused")
			String str;
		    while ((str = in.readLine()) != null) {
		        // str is one line of text; readLine() strips the newline character(s)
		    }
		    in.close();
		    initTask = new InitTask();
			initTask.execute( this );
		} catch (Exception e) {
			final AlertDialog.Builder wrongAddressAlert = new AlertDialog.Builder(MainActivity.this);
			wrongAddressAlert.setTitle("This Application Needs A Working Internet Connection!");
			wrongAddressAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					int pid = android.os.Process.myPid();
					android.os.Process.killProcess(pid); finish();
				}
			});
			wrongAddressAlert.show();
		} 

		
		/*imageView = (ImageView) findViewById(R.id.imageView);
		Display display = getWindowManager().getDefaultDisplay(); 
		int newWidth = display.getWidth() - 5;
		int newHeight = display.getHeight() - 5;
		//imageView.setImageResource(R.drawable.eventurmain);
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.eventurmain);
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		
		float scaleWidth = ((float)newWidth)/width;
		float scaleHeight = ((float)newHeight)/height;
		Matrix mat = new Matrix();
		mat.postScale(scaleWidth, scaleHeight);

		try{
			Bitmap newBitmap = Bitmap.createBitmap(bitmap,0,0,width,height,mat,true);
			BitmapDrawable bmd = new BitmapDrawable(newBitmap);
			imageView.setImageDrawable(bmd);
			imageView.setScaleType(ScaleType.CENTER);
		}
		catch(Exception e){

		}*/



		

	}


	protected class InitTask extends AsyncTask<Context, Integer, String>
	{
		ProgressDialog progressDialog;
		URL url = null;
		XmlParser xmlParser = null;
		@Override
		protected String doInBackground( Context... params ) 
		{
			try {
				URL rssUrl = new URL(RSS_FEED_SOURCE);
				SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
				SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
				XMLReader myXMLReader = mySAXParser.getXMLReader();
				XmlParser myRSSHandler = new XmlParser();
				myXMLReader.setContentHandler(myRSSHandler);
				InputSource myInputSource = new InputSource(rssUrl.openStream());
				myXMLReader.parse(myInputSource);
				
				

			} catch (MalformedURLException e) {
				final AlertDialog.Builder wrongAddressAlert = new AlertDialog.Builder(MainActivity.this);
				wrongAddressAlert.setTitle("This Application Needs A Working Internet Connection!");
				wrongAddressAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						int pid = android.os.Process.myPid();
						android.os.Process.killProcess(pid); finish();
					}
				});
				wrongAddressAlert.show();


				e.printStackTrace();
			//	result.setText("Cannot connect RSS!");
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			//	result.setText("Cannot connect RSS!");
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			//	result.setText("Cannot connect RSS!");
			} catch (IOException e) {
				final AlertDialog.Builder wrongAddressAlert = new AlertDialog.Builder(MainActivity.this);
				wrongAddressAlert.setTitle("This Application Needs A Working Internet Connection!");
				wrongAddressAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						int pid = android.os.Process.myPid();
						android.os.Process.killProcess(pid); finish();
					}
				});
				wrongAddressAlert.show();

				e.printStackTrace();
			//	result.setText("Cannot connect RSS!");
			}

			progressDialog.cancel();
			return "COMPLETE!";
		}

		/*public boolean isOnline() {
			ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		    NetworkInfo netInfo = cm.getActiveNetworkInfo();
		    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
		        return true;
		    }
		    return false;


			}*/

		@Override
		protected void onPreExecute() 
		{
			super.onPreExecute();
			Log.i( "Main", "onPreExecute()" );
			/*if(!isOnline()){
				final AlertDialog.Builder wrongAddressAlert = new AlertDialog.Builder(MainActivity.this);
				wrongAddressAlert.setTitle("This Application Needs A Working Internet Connection!");
				wrongAddressAlert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						int pid = android.os.Process.myPid();
						android.os.Process.killProcess(pid); finish();
					}
				});
				wrongAddressAlert.show();
			}
			else{*/
			progressDialog = new ProgressDialog(MainActivity.this);
			progressDialog.setMessage("Collecting Latest Events...");
			progressDialog.setCancelable(false);
			progressDialog.setIndeterminate(true);
			progressDialog.show();
			//}

		}

		@Override
		protected void onProgressUpdate(Integer... values) 
		{
			super.onProgressUpdate(values);
			Log.i( "Main", "onProgressUpdate(): " +  String.valueOf( values[0] ) );
			/*percentField.setText( ( values[0] * 2 ) + "%");
			percentField.setTextSize( values[0] );*/
		}

		// -- called if the cancel button is pressed
		@Override
		protected void onCancelled()
		{
			super.onCancelled();
			Log.i( "Main", "onCancelled()" );
			//percentField.setText( "Cancelled!" );
			//percentField.setTextColor( 0xFFFF0000 );
		}

		@Override
		protected void onPostExecute( String result ) 
		{
			super.onPostExecute(result);
			/*AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
			alertDialog.setMessage("Done Dude");
			alertDialog.show();
			 */
			/*Log.i( "makemachine", "onPostExecute(): " + result );
			percentField.setText( result );
			percentField.setTextColor( 0xFF69adea );*/
			//cancelButton.setVisibility( View.INVISIBLE );

			Intent intent = new Intent(MainActivity.this, HomeActivity.class);
			//Bundle b = new Bundle();
			//System.out.println("position in list:"+position);
			//System.out.println("title name in the list:"+eventTitleArray[position]);
			//b.putString("eventTitle", eventTitleArray[position]);
			//intent.putExtras(b);
			startActivity(intent);
			finish();


		}
	}    
}